package com.first.nell.info

import android.annotation.SuppressLint
import android.view.View
import android.widget.Toast
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.first.nell.R
import com.first.nell.base.BaseActivity
import com.first.nell.components.dialog.NgnCityPickerDialog
import com.first.nell.components.dialog.DatePickerDialog
import com.first.nell.components.dialog.PopListDialog
import com.first.nell.components.dialog.VndCityPickerDialog
import com.first.nell.data.ReqGetBankList
import com.first.nell.data.ReqSaveInfo
import com.first.nell.databinding.ActivityFirstNellInfoBinding
import com.first.nell.enums.PageTagEnum
import com.first.nell.extend.*
import com.first.nell.launch.UserStateViewModel
import com.first.nell.network.ApiUrl
import com.first.nell.utils.InfoProcessUtil
import com.first.nell.utils.UsageCountryUtil


@SuppressLint("CustomSplashScreen")
class InfoActivity : BaseActivity() {

    private lateinit var mFirstNellActivityFirstNellBinding: ActivityFirstNellInfoBinding
    private lateinit var mInfoPageFieldsAdapter: InfoPageFieldsAdapter
    private lateinit var mProxyyFp8ayr7DrIQHKHtjPg: InfoPageStepAdapter
    private lateinit var mDatePickerDialog: DatePickerDialog
    private lateinit var mPopListDialog: PopListDialog
    private lateinit var mNgnCityPickerDialog: NgnCityPickerDialog
    private lateinit var mVndCityPickerDialog: VndCityPickerDialog

    private val mInfoViewModel by lazy {
        ViewModelProvider(this).get(InfoViewModel::class.java)
    }

    private val mUserStateViewModel by lazy {
        ViewModelProvider(this).get(UserStateViewModel::class.java)
    }

    override fun onFirstNellBindingFirstNellViewFirstNellModel(): List<ViewModel>? {
        val list = mutableListOf<ViewModel>()
        list.add(mInfoViewModel)
        list.add(mUserStateViewModel)
        return list
    }

    override fun onFirstNellBindingFirstNellViewFirstNellTag(): String {
        return PageTagEnum.info.name.uppercase()
    }

    override fun onFirstNellBindingFirstNellContentFirstNellView(): View {
        mFirstNellActivityFirstNellBinding = ActivityFirstNellInfoBinding.inflate(layoutInflater)
        return mFirstNellActivityFirstNellBinding.root
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onFirstNellContentFirstNellViewFirstNellBinded() {
        try {
            //初始化pop控件
            mPopListDialog = PopListDialog()
            mPopListDialog.setFirstNellOnFirstNellItemFirstNellClickFirstNellListener { uTag, cashVistaPopListItem ->
                mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList.forEach { item ->
                    if (uTag.equals(item.title.toString(), true)) {
                        if (item.isFirstNellActionFirstNellBankFirstNellPick()) {
                            item.fillContent =
                                cashVistaPopListItem.display + "#" + cashVistaPopListItem.content
                        } else {
                            item.fillContent = cashVistaPopListItem.display
                        }
                    }
                }
                mInfoPageFieldsAdapter.notifyDataSetChanged()
            }

            //初始化地址框-越南
            mVndCityPickerDialog =
                VndCityPickerDialog.generateFirstNellDialog(getString(R.string.first_nell_select))
            mVndCityPickerDialog.setFirstNellOnFirstNellCompletedFirstNellClickFirstNellListener {uTag, state, city ->
                mInfoViewModel.mFirstNellState = state
                mInfoViewModel.mFirstNellCity = city
                mInfoViewModel.mFirstNellArea = ""

                val address =
                    (mInfoViewModel.mFirstNellState + "#" + mInfoViewModel.mFirstNellCity + "#" + mInfoViewModel.mFirstNellArea)
                println("address:$address")
                println("address-tag:mVndCityPickerDialog")

                mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList.forEach { item ->
                    if (uTag.equals(item.title.toString(), true)) {
                        item.fillContent = address
                    }
                }
                mInfoPageFieldsAdapter.notifyDataSetChanged()
            }

            //初始化地址框-尼日
            mNgnCityPickerDialog =
                NgnCityPickerDialog.generateFirstNellDialog(getString(R.string.first_nell_select))
            mNgnCityPickerDialog.setFirstNellOnFirstNellDataFirstNellClickFirstNellListener { uTag, pickType, dialogListItem, i ->
                when (pickType) {
                    R.integer.PickerTypeState -> {
                        mInfoViewModel.mFirstNellState = dialogListItem.content
                        mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                            R.integer.PickerTypeCity,
                            mInfoViewModel.getFirstNellCityFirstNellList(
                                mInfoViewModel.mFirstNellState
                            )
                        )
                    }
                    R.integer.PickerTypeCity -> {
                        mInfoViewModel.mFirstNellCity = dialogListItem.content
                        mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                            R.integer.PickerTypeTown,
                            mInfoViewModel.getFirstNellAreaFirstNellList(
                                mInfoViewModel.mFirstNellState,
                                mInfoViewModel.mFirstNellCity
                            )
                        )
                    }
                    R.integer.PickerTypeTown -> {
                        mInfoViewModel.mFirstNellArea = dialogListItem.content
                    }
                    R.integer.PickerTypeStateReload -> {
                        mInfoViewModel.mFirstNellState = ""
                        mInfoViewModel.mFirstNellCity = ""
                        mInfoViewModel.mFirstNellArea = ""
                        mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                            R.integer.PickerTypeState,
                            mInfoViewModel.getFirstNellStateFirstNellList()
                        )
                    }
                    R.integer.PickerTypeCityReload -> {
                        mInfoViewModel.mFirstNellCity = ""
                        mInfoViewModel.mFirstNellArea = ""
                        mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                            R.integer.PickerTypeCity,
                            mInfoViewModel.getFirstNellCityFirstNellList(
                                mInfoViewModel.mFirstNellState
                            )
                        )
                    }
                    R.integer.PickerTypeTownReload -> {

                    }
                    R.integer.PickerTypeConfirm -> {
                        mInfoViewModel.mFirstNellState =
                            mNgnCityPickerDialog.mFirstNellState
                        mInfoViewModel.mFirstNellCity =
                            mNgnCityPickerDialog.mFirstNellCity
                        mInfoViewModel.mFirstNellArea =
                            mNgnCityPickerDialog.mFirstNellArea
                        val address =
                            (mInfoViewModel.mFirstNellState + "#" + mInfoViewModel.mFirstNellCity + "#" + mInfoViewModel.mFirstNellArea)
                        println("address:$address")
                        println("address-tag:$uTag")

                        mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList.forEach { item ->
                            if (uTag.equals(item.title.toString(), true)) {
                                item.fillContent = address
                            }
                        }
                        mInfoPageFieldsAdapter.notifyDataSetChanged()
                    }
                }
            }

            //初始化日期框
            mDatePickerDialog = DatePickerDialog()
            mDatePickerDialog.mFirstNellDateFirstNellMode =
                R.integer.ActionModeDatePickerYYMMDD
            mDatePickerDialog.mFirstNellOnFirstNellActionFirstNellListener = { uTag, date ->
                mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList.forEach { item ->
                    if (uTag.equals(item.title.toString(), true)) {
                        item.fillContent = date
                    }
                }
                mInfoPageFieldsAdapter.notifyDataSetChanged()
            }

            //初始化列表
            mInfoPageFieldsAdapter =
                InfoPageFieldsAdapter(mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList)
            mInfoPageFieldsAdapter.setFirstNellOnFirstNellItemFirstNellClickFirstNellListener { i, revObjUserProcessPageConfigFields ->
                if (revObjUserProcessPageConfigFields.isFirstNellActionFirstNellDateFirstNellPick()) {
                    mDatePickerDialog.showFirstNellWithFirstNellUIFirstNellTag(
                        revObjUserProcessPageConfigFields.title.toString(),
                        supportFragmentManager,
                    )
                } else if (revObjUserProcessPageConfigFields.isFirstNellActionFirstNellAddressFirstNellPick()) {

                    if (UsageCountryUtil.isFirstNellCountryFirstNellVietnam()) {
                        if (!mVndCityPickerDialog.isVisible) {
                            mVndCityPickerDialog.showFirstNellWithFirstNellUIFirstNellTag(
                                revObjUserProcessPageConfigFields.title.toString(),
                                supportFragmentManager
                            )
                        }
                    } else {
                        mNgnCityPickerDialog.mFirstNellState =
                            mInfoViewModel.mFirstNellState
                        mNgnCityPickerDialog.mFirstNellCity =
                            mInfoViewModel.mFirstNellCity
                        mNgnCityPickerDialog.mFirstNellArea =
                            mInfoViewModel.mFirstNellArea
                        if (mInfoViewModel.mFirstNellState.isEmpty()) {
                            mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                                R.integer.PickerTypeState,
                                mInfoViewModel.getFirstNellStateFirstNellList()
                            )
                        } else if (mInfoViewModel.mFirstNellCity.isEmpty()) {
                            mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                                R.integer.PickerTypeCity,
                                mInfoViewModel.getFirstNellCityFirstNellList(
                                    mInfoViewModel.mFirstNellState
                                )
                            )
                        } else if (mInfoViewModel.mFirstNellArea.isEmpty()) {
                            mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                                R.integer.PickerTypeTown,
                                mInfoViewModel.getFirstNellAreaFirstNellList(
                                    mInfoViewModel.mFirstNellState,
                                    mInfoViewModel.mFirstNellCity
                                )
                            )
                        } else {
                            mNgnCityPickerDialog.setFirstNellDataFirstNellList(
                                R.integer.PickerTypeState,
                                mInfoViewModel.getFirstNellStateFirstNellList()
                            )
                        }

                        if (!mNgnCityPickerDialog.isVisible) {
                            mNgnCityPickerDialog.showFirstNellWithFirstNellUIFirstNellTag(
                                revObjUserProcessPageConfigFields.title.toString(),
                                supportFragmentManager
                            )
                        }
                    }
                } else if (revObjUserProcessPageConfigFields.isFirstNellActionFirstNellBankFirstNellPick()) {
                    //选择银行列表
                    if (mInfoViewModel.mFirstNellBankFirstNellCodeFirstNellList.isNotEmpty()) {
                        mPopListDialog.showFirstNellWithFirstNellDataFirstNellList(
                            fragmentManager = supportFragmentManager,
                            dataList = mInfoViewModel.mFirstNellBankFirstNellCodeFirstNellList,
                            gTag = revObjUserProcessPageConfigFields.title.toString()
                        )
                    } else {
                        mInfoViewModel.fetchFirstNellBankFirstNellCodeFirstNellList(
                            ReqGetBankList(uITag = revObjUserProcessPageConfigFields.title.toString())
                        )
                    }
                }
            }
            mFirstNellActivityFirstNellBinding.rcInfoFieldList.layoutManager =
                LinearLayoutManager(this)
            mFirstNellActivityFirstNellBinding.rcInfoFieldList.adapter = mInfoPageFieldsAdapter

            //初始化步骤列表
            mProxyyFp8ayr7DrIQHKHtjPg =
                InfoPageStepAdapter(mInfoViewModel.mFirstNellInfoFirstNellStepFirstNellList)
            val rcInfoStepLinearLayoutManager = LinearLayoutManager(this)
            rcInfoStepLinearLayoutManager.orientation = LinearLayoutManager.HORIZONTAL
            mFirstNellActivityFirstNellBinding.rcInfoStepList.layoutManager =
                rcInfoStepLinearLayoutManager
            mFirstNellActivityFirstNellBinding.rcInfoStepList.adapter = mProxyyFp8ayr7DrIQHKHtjPg

            //保存数据回调
            mInfoViewModel.onFirstNellSaveFirstNellInfoFirstNellLiveData.observe(this) {
                if (it.isSuccess) {
                    //记录埋点
                    mFirstNellActivityFirstNellBinding.submitInfo.recordFirstNellEvent(
                        type = mFirstNellActivityFirstNellBinding.submitInfo.getFirstNellScenFirstNellPageFirstNellEndFirstNellFlag(
                            "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mFirstNellCurrentFirstNellPageFirstNellConfig.pageNameSource?.uppercase()}"
                        ),
                        remark = ""
                    )

                    //继续走下一步
                    mUserStateViewModel.fetchFirstNellUserFirstNellState()
                }
            }

            //获取用户状态回调
            mUserStateViewModel.onFirstNellFetchFirstNellUserFirstNellStateFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //继续刷新ui
                    mInfoViewModel.initFirstNellPageFirstNellConfig()
                }
            }

            //完成所有认证信息回调
            mInfoViewModel.onFirstNellAllFirstNellPageFirstNellConfigFirstNellFinishFirstNellLiveData.observe(
                this
            ) {
                if (it) {
                    startFirstNellToFirstNellNextFirstNellFromFirstNellPage(PageTagEnum.info)
                }
            }

            //初始化页面配置完成回调
            mInfoViewModel.onFirstNellInitFirstNellPageFirstNellConfigFirstNellFinishFirstNellLiveData.observe(
                this
            ) {
                //设置显示标题
                mFirstNellActivityFirstNellBinding.topNavBarInfo.setFirstNellCenterFirstNellText(
                    it.pageName.toString()
                )

                //是否展示顶部tips
                if (it.showTopTips?.equals("YES", true) == true) {
                    mFirstNellActivityFirstNellBinding.cardInfoStepBg.visibility = View.VISIBLE
                } else {
                    mFirstNellActivityFirstNellBinding.cardInfoStepBg.visibility = View.GONE
                }

                //刷新步骤
                mProxyyFp8ayr7DrIQHKHtjPg.notifyDataSetChanged()

                //刷新项目
                mInfoPageFieldsAdapter.notifyDataSetChanged()

                //滑动到最顶部
                mFirstNellActivityFirstNellBinding.scrollInfoView.scrollTo(0, 0)
                mFirstNellActivityFirstNellBinding.rcInfoFieldList.scrollTo(0, 0)

                //记录埋点
                mFirstNellActivityFirstNellBinding.submitInfo.recordFirstNellEvent(
                    type = mFirstNellActivityFirstNellBinding.submitInfo.getFirstNellScenFirstNellPageFirstNellStartFirstNellFlag(
                        "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mFirstNellCurrentFirstNellPageFirstNellConfig.pageNameSource?.uppercase()}"
                    ),
                    remark = ""
                )
            }

            //获取银行列表回调
            mInfoViewModel.onFirstNellFetchFirstNellBankFirstNellCodeFirstNellListFirstNellLiveData.observe(
                this
            ) {
                if (it.isSuccess) {
                    //继续刷新ui
                    it.getOrNull()?.let { result ->
                        mInfoViewModel.initFirstNellBankFirstNellCodeFirstNellList(result.obj)
                        mPopListDialog.showFirstNellWithFirstNellDataFirstNellList(
                            fragmentManager = supportFragmentManager,
                            dataList = mInfoViewModel.mFirstNellBankFirstNellCodeFirstNellList,
                            gTag = result.uITag.toString()
                        )
                    }
                }
            }

            //点击保存
            mFirstNellActivityFirstNellBinding.submitInfo.setOnClickListener {
                val formDataCompleteState =
                    isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted()
                mFirstNellActivityFirstNellBinding.submitInfo.recordFirstNellEvent(
                    type = mFirstNellActivityFirstNellBinding.submitInfo.getFirstNellScenFirstNellClickFirstNellFlag(
                        "${PageTagEnum.info.name.uppercase()}_${mInfoViewModel.mFirstNellCurrentFirstNellPageFirstNellConfig.pageNameSource?.uppercase()}"
                    ),
                    remark = formDataCompleteState
                )
                if (formDataCompleteState.isBlank()) {
                    //调接口保存
                    val pageConfig =
                        InfoProcessUtil.getFirstNellCurrentFirstNellStepFirstNellPageFirstNellConfig()
                    pageConfig?.let { gPageConfig ->
                        val targetUrl = ApiUrl.BASE_URL + ApiUrl.BASE_PATH + gPageConfig.apiUrl
                        val params = mInfoViewModel.getFirstNellCurrentFirstNellParams()
                        val reqSaveInfo =
                            ReqSaveInfo(targetUrl = targetUrl, params = params)
                        mInfoViewModel.saveFirstNellInfo(reqSaveInfo)
                    }
                } else {
                    Toast.makeText(
                        this,
                        getString(R.string.first_nell_please_complete_all_required_fields),
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }

            //初始化页面配置
            mInfoViewModel.initFirstNellPageFirstNellConfig()

        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun isFirstNellAllFirstNellFormFirstNellDataFirstNellCompleted(): String {
        val notFillOptions = mutableListOf<String>()
        mInfoViewModel.mFirstNellInfoFirstNellFieldFirstNellList.forEach { item ->
            println("name: ${item.paramName}")
            println("fillContent: ${item.fillContent}")
            item.needCheckComplete = true

            if (item.isFirstNellActionFirstNellContactFirstNellGroup()) {
                item.subDataList?.let { subList ->
                    subList.forEach { subItem ->
                        subItem.needCheckComplete = true
                        println("subItem name: ${subItem.paramName}")
                        println("subItem fillContent: ${subItem.fillContent}")
                        if (!subItem.isFirstNellCompleted()) {
                            notFillOptions.add(subItem.paramName.toString())
                        }
                    }
                }
            } else {
                if (!item.isFirstNellCompleted()) {
                    notFillOptions.add(item.paramName.toString())
                }
            }
        }
        mInfoPageFieldsAdapter.notifyDataSetChanged()
        if (notFillOptions.isEmpty()) {
            return ""
        }
        notFillOptions.add(0, "NOT_FILL")
        return notFillOptions.joinToString("#")
    }
}